<?php

/**
 * CelebrioMail PeopleManagement
 *
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    PeopleManagement
 */
namespace ApplicationsModule\PeopleModule;


use Nette\Object;
use Nette\String;
use Nette\Environment;
use Celebrio\Core\ServiceProvider;
use Celebrio\Modules;
use Celebrio\Util\CacheName;

use \dibi;

/**
 * 
 * @author pavel
 */
class Facebook extends DummyContactService implements IContactService {

    const FACEBOOK = "facebook";


    private $celebrio_app_id = "133331463420857";
    private $celebrio_app_secret = "2e1f8f2f182e00be34c0af6140660235";
    
    private $walterWegoAccessKey = "133331463420857|8ee21116cb3050f030166288.1-100002763660222|Ki3Lb_jPLgnWd1VFJLGBa-u9qis";

    private $facebook;

    /** @var \Nette\Caching\Cache */
    private $cache;

    // archive call - the first one which worked. however, it still sux
    // $url = "https://graph.facebook.com/search?access_token=$access_token&q="
    //        . urlencode($name) . "&type=$type&limit=$limit"; // default limit is probably 25

    public function __construct() {
        $appInfo = array(
          'appId'  => $this->celebrio_app_id,
          'secret' => $this->celebrio_app_secret,
        );

        $this->facebook = new \Facebook($appInfo);
        $this->facebook->setAccessToken($this->walterWegoAccessKey);

        $this->cache = CacheName::generate($this);
    }

    
    // ----------------------------------------------------------------------------------------------------------//

    static function getServiceName() {
        return self::FACEBOOK;
    }

    static function providedRows(array $exclude = array()) {
        return array(
            array("db" => "uid", "display" => false, "protected" => false, "unique" => true),
            array("db" => "fb_pass", "display" => false, "protected" => true)
        );
    }

    public function getIdentifier($personId) {
        throw new \NotImplementedException;
    }

    public function addPerson(Person $person, array $other_info = null) {
        $fb_contact = array("id_person" => $person->getId(), "uid" => $other_info["uid"]);
        dibi::insert("contacts_facebook", $fb_contact)->execute();
    }

//    public function getContact($uid) {
//        if ($this->cache->offsetExists($uid)) {
//            $contact = $this->cache->offsetGet($uid);
//        } else {
//            $user = $this->facebook->api($uid);
//            $contact = new Contact($user["id"], $user["first_name"], $user["last_name"]);
//            $contact->setProfilePicture('http://graph.facebook.com/' . $user['uid'] . "/picture?type=large");
//            $this->cache->offsetSet($contact->getId(), $contact);
//        }
//        return $contact;
//    }

    public function search($info) {
        $name = urlencode(trim($info["first_name_person"] . " " . $info["last_name_person"]));
        $users = $this->facebook->api("/search?q=$name&type=user&access_token=$this->walterWegoAccessKey");

        if (isset($users["data"]))
        {
            $people_found = array();
            foreach ($users["data"] as $user)
            {
                $name = explode(" ", $user["name"], 2);
                $uid = $user["id"];
                $person = new Person($name[0], $name[1], "http://graph.facebook.com/$uid/picture?type=large");
                $person->addToAdditionalInfo("uid", $uid);
                $people_found[] = $person;
            }

        }
        else
        {
            throw new \Exception("Erroneous data received from facebook.");
        }
        
        return $people_found;

    }

    /**
     * @param $name
     * @param string $type
     * @return array(Contact)
     */
    private function fql_search($info) {
        $uid = $info['uid'];
        if (!empty($uid)) {
            $search_for = $uid;
            $search_by = "uid";
        } else {
            $search_for = $info['first_name_person'] . " " . $info['last_name_person'];
            $search_for = preg_replace("/'/", "\\'", $search_for);
            $search_by = "name";
        }
        $users = $this->facebook->api(array(
            'method' => 'fql.query',
            'query' => "SELECT first_name,last_name,uid,name FROM user WHERE $search_by='$search_for'",
        ));

        $people_found = array();
        foreach ($users as $user) {
            $person = new Person($user["first_name"], $user["last_name"]);
            $person->setProfilePicture('http://graph.facebook.com/' . $user['uid'] . "/picture?type=large");
            $person->addToAdditionalInfo("uid", $user["uid"]);
//            $this->cache->offsetSet($contact->getId(), $contact);
            $people_found[] = $person;
        }
        
        return $people_found;
    }

}